<template>
    <Card>
        <!--搜索条件-->
        <Select v-model="type" style="width:20%;padding-left:20px" @on-change="getData(1)">
            <Option v-for="item in list1" :value="item.type" :key="item.type">{{ item.name }}</Option>
        </Select>
        <Select v-model="time" style="width:20%;margin-left:10px;" @on-change="changeTimeRange">
            <Option v-for="item in list2" :value="item.time" :key="item.time">{{ item.name }}</Option>
        </Select>
    
        <DatePicker 
            v-show="time==3"
            :clearable="false" 
            type="daterange" 
            placeholder="选择时间段" 
            style="width:20%;margin-left:10px;" 
            v-model="timeRange"></DatePicker>
        
        <Button type="primary" icon="ios-search" style="margin-left:10px;"  @click="getData(1)">搜索</Button>            
        <Button type="primary" style="margin-left:10px;" @click="getCurrentElemeter" :loading="isRefreshElemeterData" v-if="recordType==0">获取最新电量</Button> 
        <Button type="primary" style="margin-left:10px;" @click="getCurrentWatermeter" v-if="recordType==1">获取最新用水</Button>           
        <Button type="primary" style="margin-left:10px;" @click="exportTable">导出报表</Button>           
        <!--搜索条件end-->          
        <br>
        <br>

        <!--表格数据-->
        <Table stripe border 
        :columns="columns[recordType]" 
        :data="datas.slice( (currentPage-1) *size, currentPage*size )"
        size="small" :loading="isLoadig"></Table>
        <!--表格数据end-->



        <!--分页-->
        <Page :total="total" 
        :page-size="size" 
        :current.sync="currentPage"
        show-elevator 
        v-if="recordType!=0"
        @on-change="getData"
        show-total style="text-align:center"></Page>
        <!--分页end-->

        <!--用电记录无分页，前端分页-->
        <Page :total="total" 
        :page-size="size" 
        :current.sync="currentPage"
        show-elevator 
        v-if="recordType==0"
        show-total style="text-align:center"></Page>
        <!--用电记录无分页，前端分页end-->

    </Card> 
</template> 

<script>
import { http, api } from '@/libs/http'
import util from '@/libs/util'
import dayjs from 'dayjs'
const now = dayjs().endOf('day').valueOf()
const timeBefore3 = dayjs().add(-3, 'days').startOf('day').valueOf()
const timeBefore7 = dayjs().add(-7, 'days').startOf('day').valueOf()
const timeBefore30 = dayjs().add(-30, 'days').startOf('day').valueOf()
export default {
  name: 'abnormal_report',
  props: {
    recordType: {
      // recordType: 0 电表记录;  1 水表记录;
      default: 1,
      required: true
    },
    room: {
      required: true
    }
  },
  data () {
    let columns1 = [
      {
        align: 'center',
        title: '时间',
        // key: 'time',
        render: (createElement, obj) => {
          return createElement(
            'span', // 标签名称
            new Date(obj.row.time).Format(this.type === 'hour' ? 'yyyy-MM-dd HH:mm' : 'yyyy-MM-dd')
          )
        }
      },
      {
        align: 'center',
        title: '电表读数',
        key: 'elemeter_read',
        render (createElement, obj) {
          const read = obj.row.elemeter_read
          const result = read === undefined || read === null ? '-' : Math.round(read * 100) / 100
          return createElement('span', result)
        }
      }
    ]

    let columns2 = [
      {
        align: 'center',
        title: '时间',
        // key: 'time',
        render: (createElement, obj) => {
          return createElement(
            'span', // 标签名称
            new Date(obj.row.time).Format(this.type === 'hour' ? 'yyyy-MM-dd HH:mm' : 'yyyy-MM-dd')
          )
        }
      },
      {
        align: 'center',
        title: '水表读数（吨）',
        key: 'amount',
        render (createElement, obj) {
          const item = obj.row.amount
          const result = item == null || item === undefined ? '-' : Math.round(item * 100) / 100
          return createElement(
            'span', // 标签名称
            result
          )
        }
      }
    ]

    return {
      refreshTimes: 0,
      lastElemeterDataLength: Infinity,
      isLoadig: false,
      isRefreshElemeterData: false,
      size: 20,
      total: 0,
      currentPage: 1,
      columns: [columns1, columns2],
      roomInfo: {},
      isOverdraft: false,
      datas: [],
      type: 'day',
      rechargeType: 0,
      time: 0,
      timeRange: [new Date(timeBefore3), new Date(now)],
      list1: [
        {
          type: 'hour',
          name: '按小时展示'
        },
        {
          type: 'day',
          name: '按天展示'
        }
      ],
      list2: [
        {
          time: 0,
          name: '最近三天'
        },
        {
          time: 1,
          name: '最近七天'
        },
        {
          time: 2,
          name: '最近一个月'
        },
        {
          time: 3,
          name: '自定义'
        }
      ],
      list3: [
        {
          recharge: 0,
          name: '充值渠道'
        },
        {
          recharge: 1,
          name: '支付宝'
        },
        {
          recharge: 2,
          name: '微信'
        },
        {
          recharge: 3,
          name: '人工充值'
        }
      ]
    }
  },
  created () {
    this.getData(1) // 获取第一页全部数据
  },
  methods: {
    getData (page, select) {
      if (page === 1) {
        this.currentPage = 1
      }
      let roomId = this.room.roomId
      let deviceId = this.room.id

      let params = {
        limit: this.size,
        offset: this.size * (page - 1)
      }
      let startTime = new Date(this.timeRange[0]).getTime()
      let endTime = new Date(this.timeRange[1]).getTime()
      if (select) {
        switch (this.time) {
          case 0:
            startTime = timeBefore3
            endTime = now
            break
          case 1:
            startTime = timeBefore7
            endTime = now
            break
          case 2:
            startTime = timeBefore30
            endTime = now
            break
        }
      }
      endTime = dayjs(endTime).endOf('day').valueOf() // 最终传给后端的end_time时间 23:59:59
      this.timeRange = [new Date(startTime), new Date(endTime)]

      let apiPath
      switch (this.recordType) {
        case 0:
          // 用电
          params.type = this.type
          params.start_time = startTime
          params.end_time = endTime
          apiPath = api.room_elemeter_record
          break
        case 1:
          // 用水
          params.type = this.type
          params.start_time = startTime
          params.end_time = endTime
          apiPath = api.room_watermeter_record
          break
      }
      this.isLoadig = true
      util.log('startTime', new Date(params.start_time).Format('yyyy-MM-DD HH:mm'))
      util.log('endTime', new Date(params.end_time).Format('yyyy-MM-DD HH:mm'))
      http.request(this, apiPath, [roomId, deviceId], params, res => {
        if (res) {
          // 电表记录
          switch (this.recordType) {
            case 0:
              // 返回的是一个对象，转化为数组
              const transferedData = this.transferData(res)

              this.datas = transferedData.result
              this.total = transferedData.total

              this.$emit('on-elemeter-left', this.datas[0])
              break
            case 1:
              // 用水
              let records = res.records.reverse()

              this.datas = records || []
              this.total = records.length || 0

              break
          }
        }
        this.isLoadig = false
      })
    },

    /**
         * 转换电表记录数据
         * @param { Object } recordDatas 用电记录数据
         * @return { Object } 数据总数 total 数据数组 result
         */
    transferData (recordDatas) {
      let total = 0 // 数据总条数
      let result = []
      let lastElemeterRead = 0

      Object.keys(recordDatas).sort().forEach(time => {
        // 构造数据

        const singleDataItem = {} // 单条数据
        const originData = recordDatas[time]

        if (originData.consume !== null) {
          singleDataItem.elemeterUsed = originData.elemeter_read - lastElemeterRead
          lastElemeterRead = originData.elemeter_read
        }

        singleDataItem.time = +time
        singleDataItem.elemeter_read = originData.elemeter_read
        singleDataItem.consume = originData.consume

        result.push(singleDataItem)

        total++
      })

      result.reverse()
      return { total, result }
    },
    changeTimeRange () {
      this.getData(1, true)
    },
    exportTable () {
      let roomId = this.room.roomId
      let deviceId = this.room.id
      let params = {}
      let startTime = new Date(this.timeRange[0]).getTime()
      let endTime = new Date(this.timeRange[1]).getTime()

      let apiPath
      switch (this.recordType) {
        case 0:
          // 用电
          params.type = this.type
          params.start_time = startTime
          params.end_time = endTime
          params.download = true
          apiPath = api.room_elemeter_record
          break
        case 1:
          // 用水
          params.type = this.type
          params.start_time = startTime
          params.end_time = endTime
          apiPath = api.room_watermeter_record_export
          break
      }
      // 导出报表
      http.exportTable(this, apiPath, [roomId, deviceId], params)
    },
    getCurrentElemeter () {
      // 获取最新电量 elemeter_read
      const { roomId, id: deviceId } = this.room
      // let deviceId = this.room.id
      http.request(this, api.elemeter_read, [roomId, deviceId], null, res => {
        if (res) {
          this.$Message.success('抄表指令已发送,请稍后..')

          setTimeout(() => {
            this.type = 'hour'
            this.getData()
          }, 3000)
        }
      })
    },
    getCurrentWatermeter () {
      // 获取最新水表 watermeter_action_read
      let roomId = this.room.roomId
      let deviceId = this.room.id
      http.request(this, api.watermeter_action_read, [roomId, deviceId], null, res => {
        if (res) {
          this.$Message.success('抄表指令已发送,请稍后...')

          setTimeout(() => {
            this.type = 'hour'
            this.getData()
          }, 3000)
        }
        this.isLoadig = false
      })
    }
  }
}
</script>

<style lang="less">
.export-link {
    color: #fff;
    text-decoration: none;
}
.export-link:hover {
    color: #fff;
}
</style>
